const BloomFilter = require("../template")

function testBloomFilterStatistics() {
  console.log(
    "1. 位数组密度统计测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 添加数据并观察密度变化
      const densities = []
      for (let i = 0; i < 100; i++) {
        bf.add(`density_item${i}`)
        densities.push(bf.getBitArrayDensity())
      }
      
      // 密度应该逐渐增加
      const isIncreasing = densities.every((density, index) => 
        index === 0 || density >= densities[index - 1]
      )
      
      return isIncreasing &&
             densities[0] > 0 &&
             densities[99] <= 1 &&
             bf.getItemCount() === 100
    })()
  )

  console.log(
    "2. 假阳性率统计测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 添加数据并观察假阳性率变化
      const rates = []
      for (let i = 0; i < 200; i++) {
        bf.add(`rate_item${i}`)
        rates.push(bf.getFalsePositiveRate())
      }
      
      // 假阳性率应该逐渐增加
      const isIncreasing = rates.every((rate, index) => 
        index === 0 || rate >= rates[index - 1]
      )
      
      return isIncreasing &&
             rates[0] >= 0 &&
             rates[199] <= 1 &&
             bf.getItemCount() === 200
    })()
  )

  console.log(
    "3. 元素数量估算测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 添加已知数量的元素
      const actualCount = 150
      for (let i = 0; i < actualCount; i++) {
        bf.add(`estimate_item${i}`)
      }
      
      const estimatedCount = bf.estimateItemCount()
      const actualItemCount = bf.getItemCount()
      
      // 估算值应该在合理范围内
      return estimatedCount >= 0 &&
             Math.abs(estimatedCount - actualCount) < actualCount * 0.5 && // 允许50%误差
             actualItemCount === actualCount
    })()
  )

  console.log(
    "4. 哈希函数分布统计测试:",
    (() => {
      const bf = new BloomFilter(100, 0.01)
      const testString = "distribution_test"
      
      // 测试哈希函数分布
      const hashFunctions = bf.getHashFunctions()
      const hashValues = hashFunctions.map(hashFunc => hashFunc(testString))
      
      // 检查哈希值是否在有效范围内
      const validHashes = hashValues.every(hash => 
        hash >= 0 && hash < bf.getBitArraySize()
      )
      
      // 检查哈希值是否不同（理想情况下应该不同）
      const uniqueHashes = new Set(hashValues)
      
      return validHashes &&
             hashValues.length === bf.getHashFunctionCount() &&
             uniqueHashes.size > 1 // 至少应该有一些不同的哈希值
    })()
  )

  console.log(
    "5. 位数组利用率统计测试:",
    (() => {
      const bf = new BloomFilter(500, 0.01)
      
      // 添加数据并计算利用率
      const utilizations = []
      for (let i = 0; i < 50; i++) {
        bf.add(`util_item${i}`)
        const density = bf.getBitArrayDensity()
        const utilization = density * 100 // 转换为百分比
        utilizations.push(utilization)
      }
      
      // 利用率应该逐渐增加
      const isIncreasing = utilizations.every((util, index) => 
        index === 0 || util >= utilizations[index - 1]
      )
      
      return isIncreasing &&
             utilizations[0] > 0 &&
             utilizations[49] <= 100 &&
             bf.getItemCount() === 50
    })()
  )

  console.log(
    "6. 统计信息一致性测试:",
    (() => {
      const bf1 = new BloomFilter(1000, 0.01)
      const bf2 = new BloomFilter(1000, 0.01)
      
      // 添加相同的数据
      const items = Array.from({ length: 100 }, (_, i) => `consistency_item${i}`)
      items.forEach(item => {
        bf1.add(item)
        bf2.add(item)
      })
      
      // 统计信息应该一致
      const density1 = bf1.getBitArrayDensity()
      const density2 = bf2.getBitArrayDensity()
      const rate1 = bf1.getFalsePositiveRate()
      const rate2 = bf2.getFalsePositiveRate()
      const count1 = bf1.getItemCount()
      const count2 = bf2.getItemCount()
      
      return Math.abs(density1 - density2) < 0.001 &&
             Math.abs(rate1 - rate2) < 0.001 &&
             count1 === count2 &&
             count1 === 100
    })()
  )

  console.log(
    "7. 统计信息边界测试:",
    (() => {
      const bf = new BloomFilter(10, 0.01) // 小容量
      
      // 测试空状态
      const emptyDensity = bf.getBitArrayDensity()
      const emptyRate = bf.getFalsePositiveRate()
      const emptyCount = bf.getItemCount()
      const emptyEstimate = bf.estimateItemCount()
      
      // 添加一个元素
      bf.add("single_item")
      
      // 测试单元素状态
      const singleDensity = bf.getBitArrayDensity()
      const singleRate = bf.getFalsePositiveRate()
      const singleCount = bf.getItemCount()
      const singleEstimate = bf.estimateItemCount()
      
      return emptyDensity === 0 &&
             emptyRate >= 0 &&
             emptyCount === 0 &&
             emptyEstimate >= 0 &&
             singleDensity > 0 &&
             singleRate > emptyRate &&
             singleCount === 1 &&
             singleEstimate >= 0
    })()
  )

  console.log(
    "8. 统计信息精度测试:",
    (() => {
      const bf = new BloomFilter(2000, 0.001) // 高精度
      
      // 添加数据
      for (let i = 0; i < 100; i++) {
        bf.add(`precision_item${i}`)
      }
      
      const density = bf.getBitArrayDensity()
      const rate = bf.getFalsePositiveRate()
      const count = bf.getItemCount()
      const estimate = bf.estimateItemCount()
      
      // 检查精度
      const densityPrecision = density.toString().split('.')[1]?.length || 0
      const ratePrecision = rate.toString().split('.')[1]?.length || 0
      
      return densityPrecision >= 3 && // 至少3位小数
             ratePrecision >= 3 &&
             count === 100 &&
             estimate >= 0
    })()
  )

  console.log(
    "9. this上下文统计测试:",
    (() => {
      const statsObj = {
        threshold: 0.1,
        processStatistics: function(items) {
          const bf = new BloomFilter(1000, 0.01)
          items.forEach(item => bf.add(item))
          return bf.getFalsePositiveRate() < this.threshold
        }
      }
      
      const items = Array.from({ length: 50 }, (_, i) => `stats_item${i}`)
      return statsObj.processStatistics(items) === true
    })()
  )

  console.log(
    "10. 复杂对象this绑定统计测试:",
    (() => {
      const statsConfigObj = {
        config: { maxDensity: 0.5 },
        processWithConfig: function(items) {
          const bf = new BloomFilter(1000, 0.01)
          items.forEach(item => bf.add(item))
          return bf.getBitArrayDensity() <= this.config.maxDensity
        }
      }
      
      const items = Array.from({ length: 100 }, (_, i) => `config_item${i}`)
      return statsConfigObj.processWithConfig(items) === true
    })()
  )

  console.log(
    "11. 统计信息趋势分析测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 记录统计信息变化趋势
      const trends = {
        densities: [],
        rates: [],
        counts: [],
        estimates: []
      }
      
      for (let i = 0; i < 50; i++) {
        bf.add(`trend_item${i}`)
        trends.densities.push(bf.getBitArrayDensity())
        trends.rates.push(bf.getFalsePositiveRate())
        trends.counts.push(bf.getItemCount())
        trends.estimates.push(bf.estimateItemCount())
      }
      
      // 检查趋势
      const densityTrend = trends.densities.every((d, i) => i === 0 || d >= trends.densities[i-1])
      const rateTrend = trends.rates.every((r, i) => i === 0 || r >= trends.rates[i-1])
      const countTrend = trends.counts.every((c, i) => i === 0 || c > trends.counts[i-1])
      
      return densityTrend &&
             rateTrend &&
             countTrend &&
             trends.counts[49] === 50
    })()
  )

  console.log(
    "12. 统计信息完整性测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 添加数据
      for (let i = 0; i < 200; i++) {
        bf.add(`complete_item${i}`)
      }
      
      // 获取所有统计信息
      const stats = {
        itemCount: bf.getItemCount(),
        bitArraySize: bf.getBitArraySize(),
        hashFunctionCount: bf.getHashFunctionCount(),
        density: bf.getBitArrayDensity(),
        falsePositiveRate: bf.getFalsePositiveRate(),
        estimatedCount: bf.estimateItemCount()
      }
      
      // 验证统计信息完整性
      return stats.itemCount === 200 &&
             stats.bitArraySize > 0 &&
             stats.hashFunctionCount > 0 &&
             stats.density >= 0 && stats.density <= 1 &&
             stats.falsePositiveRate >= 0 && stats.falsePositiveRate <= 1 &&
             stats.estimatedCount >= 0 &&
             typeof stats.itemCount === 'number' &&
             typeof stats.bitArraySize === 'number' &&
             typeof stats.hashFunctionCount === 'number' &&
             typeof stats.density === 'number' &&
             typeof stats.falsePositiveRate === 'number' &&
             typeof stats.estimatedCount === 'number'
    })()
  )
}

testBloomFilterStatistics()
